
import base64
import io
import json
from multiprocessing import freeze_support 
from flask import Flask, request, jsonify
import time
from PIL import Image


from digital_5 import DigitalProcessor_5
app = Flask(__name__)
# 设置开启web服务后，如果更新html文件，可以使更新立即生效
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['JSON_AS_ASCII'] = False
# 指定浏览器渲染的文件类型，和解码格式；
app.config['JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"


# 访问首页
@app.route('/')
def index_page():
    return '-- recognition server --'



digital_5_detector = DigitalProcessor_5()

from PIL import Image

@app.route('/data/3.1.6/getPicdata', methods=['POST'])
def getPicdata():
    if request.method == 'POST':
        start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        data = request.get_data()
        json_data = json.loads(data.decode('utf-8'))
        type = json_data['type']
        picdata = json_data['picdata']
        if picdata:
            image = base64.b64decode(picdata)
            with Image.open(io.BytesIO(image)) as img:
                img.save('./5.jpg')
                try:
                    nums = digital_5_detector.call('./5.jpg')
                except:
                    return jsonify(errcode=302, errmsg="图片类型不正确", datatime=start_time, datavalue="")
            if nums == "error":
                return jsonify(errcode=301, errmsg="图片清晰度不够，无法识别", datatime=start_time, datavalue="")
            return jsonify(errcode=0, errmsg="识别成功", datatime=start_time, datavalue=nums, quality=0.0, problem=0)
        else:
            return jsonify(errcode=302, errmsg="图片类型 type 不正确。指针式为 0 ，数字式为 1 ,黑底白字是3", datatime=start_time, datavalue="")


if __name__ == '__main__':
    # freeze_support() 
    app.run(host='0.0.0.0', port='5000',threaded=False)
    # app.run(host='0.0.0.0', port='5000', processes=True)
